package v3

import (
	"github.com/gin-gonic/gin"
	"log"
	v4 "mindonmap/api/v4"
	"mindonmap/pkgs/e"
	"mindonmap/validation"
	"net/http"

	"mindonmap/models"
)

// 获取指定历史数据
func GetFeedback(c *gin.Context) {
	var json models.Feedback
	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}

	valid := validation.Validation{}
	valid.Required(json.ID, "id").Message("不能为空")

	code := e.INVALID_PARAMS
	var data interface{}
	if !valid.HasErrors() {
		if models.ExistFeedbackByID(json.ID) {
			data = models.GetFeedback(json.ID)
			code = e.SUCCESS
		} else {
			code = e.ERROR_NOT_EXIST_ARTICLE
		}
	} else {
		for _, err := range valid.Errors {
			log.Printf("err.key: %s, err.message: %s", err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// 新增脑图数据
func AddFeedback(c *gin.Context) {
	var json models.Feedback

	if err := c.BindJSON(&json); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.INVALID_PARAMS,
			"msg":  e.GetMsg(e.INVALID_PARAMS),
			"data": make(map[string]interface{}),
		})
		return
	}
	Userid, err := v4.GetUserID(c)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT,
			"msg":  e.GetMsg(e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT),
			"data": make(map[string]interface{}),
		})
		return
	}

	code := e.SUCCESS
	data := make(map[string]interface{})
	data["acid"] = Userid
	data["contents"] = json.Contents
	data["types"] = json.Types
	data["grade"] = json.Grade
	models.AddFeedback(data)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}
